<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Employee_settings extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->page_auth->secure_page(array('admin','hrd','president'));
		$this->load->model(array('M_employees', 'M_users', 'M_profile'));
		$this->load->library(array('form_validation','notifier','grocery_CRUD'));
		$this->load->helper(array('form'));
		$this->layout_view= 'application_gc';
	}
	
	public function index()
	{
		show_404();
	}
	
	public function change_settings($emp_id = '')
	{
		if($this->session->userdata('userType') !== 'hrd' AND $this->session->userdata('userType') !== 'admin')
		{
			show_error('Illegal user type.', 403);
		}
		
		$user_id = '';
		$current_uname = '';
		if($emp_id != FALSE AND is_numeric($emp_id))
		{
			$emp_user_data = $this->M_users->get_user_data_empid($emp_id);
			if(!empty($emp_user_data))
			{
				$this->view_data['emp_user_data'] = $emp_user_data;
				$this->view_data['emp_id'] = $emp_id;
				$this->view_data['system_message'] = $this->notifier->build_system_message('notice', 'Please copy generated username and/or password and give to concerned employee IMMEDIATELY. <br /><br /><p>*Password will disappear after generation.</p>');
				$user_id = $emp_user_data->id;
				$current_uname = $emp_user_data->username;
			}
			
			
			if($_POST)
			{
				if($user_id != '')
				{
					$new_uname = $this->input->post('username');
					$new_pword = $this->input->post('password');
					$msg_flag = FALSE;
					
					if($new_uname != '')
					{
						switch($new_uname)
						{
							case $current_uname: // if entry is the same from previous one.
								if($new_pword == '')
								{
									$this->view_data['system_message'] = $this->notifier->build_system_message('notice', 'No changes done.');
								}
								break;
							default:
								$flag = $this->__change_username($new_uname, $user_id);
								if($flag)
								{
									if($flag === 'duplicate')
									{
										$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'Username has already been used.');
									}else
									{
										$emp_user_data = $this->M_users->get_user_data_empid($emp_id);
										if(!empty($emp_user_data))
										{
											$this->view_data['emp_user_data'] = $emp_user_data;
											$this->view_data['emp_id'] = $emp_id;
											$this->view_data['system_message'] = $this->notifier->build_system_message('success', 'Employee username changed.');
											$user_id = $emp_user_data->id;
											$current_uname = $emp_user_data->username;
											$msg_flag = TRUE;
										}
									}
								}else
								{
									$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'There was a problem changing employee username.');
								}
								break;
						}
					}
					
					if($new_pword != '')
					{
						if($this->__change_password($new_pword, $user_id))
						{
							$emp_user_data = $this->M_users->get_user_data_empid($emp_id);
							if(!empty($emp_user_data))
							{
								$this->view_data['emp_user_data'] = $emp_user_data;
								$this->view_data['emp_id'] = $emp_id;
								if($msg_flag)
								{
									$this->view_data['system_message'] = $this->notifier->build_system_message('success', 'Employee username  and password changed.');
								}else
								{
									$this->view_data['system_message'] = $this->notifier->build_system_message('success', 'Employee password changed.');
								}
								$user_id = $emp_user_data->id;
								$current_uname = $emp_user_data->username;
							}
						}else
						{
							$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'There was a problem changing employee password.');
						}
					}
					
					
				}else
				{
					$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'There was a problem retrieving user data.');
				}
			}
		}else
		{
			show_error('Invalid employee ID.', $status_code = 401);
		}
	}
	
	public function change_password($username = '')
	{
		
		$user_data = $this->session->userdata('username');
		$this->view_data['username'] = $username;
		
		if($user_data !== $username)
		{
			show_error('Illegal use of username.', $status_code = 403);
		}
		$this->view_data['we'] = $this->notifier->build_system_message('notice', 'After changing password, you need to log-in again.');
		
		if($_POST)
		{
			$user_data = $this->M_users->get_user_data('username', $username);
			if(!empty($user_data))
			{
				foreach($user_data AS $u_data)
				{
					$user_id = $u_data->id;
				}
				$this->form_validation->set_rules('old_pword', 'Password', 'required');
				$this->form_validation->set_rules('new_pword', 'New Password');
				$this->form_validation->set_rules('conf_pword', 'Confirm Password', 'matches[new_pword]');
				
				if($this->form_validation->run())
				{
					$old_pword = $this->input->post('old_pword');
					if($this->M_users->verify_password($old_pword, $user_id))
					{
						$new_pword = $this->input->post('new_pword');
						if($this->M_users->change_pass($new_pword, $user_id))
						{
							$this->session->sess_destroy();
							$this->session->set_flashdata('system_message','Password change successful, log in to your new credentials.');
							redirect('auth/login/hrd');
						}else
						{
							$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'There was a problem changing password.');
						}
					}else
					{
						$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'Incorrect password.');
					}					
				}
			}else
			{
				$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'Unable to retrieve user data. Cannot change password.');
			}
		}
	}
	
	public function change_profile($username = '')
	{
		$user_data = $this->session->userdata('username');
		if($user_data !== $username)
		{
			show_error('Illegal use of username.', $status_code = 403);
		}
		$this->view_data['username'] = $username;
		
		$emp_data = $this->M_employees->get_employee_data('username', $username);
		if(!empty($emp_data))
		{
			$columns = $this->M_employees->get_columns();
			for($i = 0; $i < count($columns); $i++)
			{
				switch($columns[$i]->Field)
				{
					case 'emp_id':
						break;
					case 'id':
						break;
					case 'let_gov_exams_id':
						break;
					case 'contract_id':
						break;
					case 'is_adviser':
						break;
					case 'role':
						break;
					case 'userStatus':
						break;
					default:
						$column_obj[] = $columns[$i];
				}
			}
			$display = $this->__prepare_display($column_obj);
			$present_data = $this->M_employees->get_employee_data('username', $username);
			foreach($present_data AS $p)
			{
				$pres_data['given_id'] = $p->given_id;
				$pres_data['last_name'] = $p->last_name;
				$pres_data['first_name'] = $p->first_name;
				$pres_data['middle_name'] = $p->middle_name;
				$pres_data['email'] = $p->email;
				$pres_data['gender'] = $p->gender;
				$pres_data['birthdate'] = $this->_format_date_display($p->birthdate);
				$pres_data['civil_status'] = $p->civil_status;
				$pres_data['father_name'] = $p->father_name;
				$pres_data['mother_name'] = $p->mother_name;
				$pres_data['spouse_name'] = $p->spouse_name;
				$pres_data['children_num'] = $p->children_num;
				$pres_data['notes'] = $p->notes;
				$pres_data['employment_status'] = $p->employment_status;
				$pres_data['hire_date'] = $this->_format_date_display($p->hire_date);
				$pres_data['termination_date'] = $this->_format_date_display($p->termination_date);
				$pres_data['employment_status'] = $p->employment_status;
				$id = $p->id;
			}
			$this->view_data['display'] = $display;
			$this->view_data['present_data'] = $pres_data;
			$this->view_data['username'] = $username;
			$this->view_data['u_id'] = $id;
			$this->view_data['role'] = $this->session->userdata('userType');
			
			if($this->input->post('profile'))
			{
				$config = $this->__prepare_form_validation($display);
				$this->form_validation->set_rules($config);
				if($this->form_validation->run())
				{
					$data = $this->input->post('profile');
					
					if($this->M_employees->update_employee($data))
					{
						redirect('employee_settings/change_profile/' . $username, 'location');
					}else
					{
						$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'There was a problem updating data.');
					}
				}
			}
		}else
		{
			redirect('employee_settings/add_profile/' . $username, 'location');
		}
	}
	
	public function add_profile($username = '')
	{
		$user_type = $this->session->userdata('userType');
		if($user_type !== 'hrd')
		{
			show_error('Illegal user.', 403);
		}
		
		
		$columns = $this->M_employees->get_columns();
		for($i = 0; $i < count($columns); $i++)
		{
			switch($columns[$i]->Field)
			{
				case 'emp_id':
					break;
				case 'id':
					break;
				case 'let_gov_exams_id':
					break;
				case 'contract_id':
					break;
				case 'is_adviser':
					break;
				case 'role':
					break;
				case 'userStatus':
					break;
				default:
					$column_obj[] = $columns[$i];
			}
		}
		$display = $this->__prepare_display($column_obj);
		$present_data = $this->M_users->get_user_data('username', $username);
		foreach($present_data AS $p)
		{
			$username = $p->username;
			$status = $p->userStatus;
			$id = $p->id;
		}
		$this->view_data['display'] = $display;
		$this->view_data['username'] = $username;
		$this->view_data['status'] = $status;
		$this->view_data['u_id'] = $id;
		$this->view_data['role'] = $this->session->userdata('userType');
		$this->view_data['system_message'] = $this->notifier->build_system_message('notice', 'You have no recorded profile yet.');
		
		if($_POST)
		{
			$config = $this->__prepare_form_validation($display);
			$this->form_validation->set_rules($config);
			if($this->form_validation->run())
			{
				$data = $_POST['profile'];
				if($this->M_employees->insert_employee($data))
				{
					redirect('employee_settings/change_profile/' . $username, 'location');
				}else
				{
					$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'There was a problem inserting data.');
				}
			}
		}
	}
	
	function manage_employees()
	{

		$this->load->helper('student_photo');
		$this->load->model('M_departments');
		$c = new grocery_CRUD();
		$c->set_theme('datatables'); // theme datatables or flexigrid
		$c->where('userStatus','active');
		$c->set_table('employees'); // Set table to use...
		$c->set_subject('Employee');
		$c->order_by('last_name', 'asc');
		
		$c->unique_fields('given_id');
		
		// Modify columns to be displayed
		$c->columns('given_id', 'last_name', 'first_name', 'middle_name', 'role', 'userStatus','image');

		
		
		$c->callback_column('image',array($this,'profilePicture'));

		$c->display_as('given_id', 'User Name/Password')
			->display_as('last_name', 'Last Name')
			->display_as('first_name', 'First Name')
			->display_as('middle_name', 'Middle Name')
			->display_as('role', 'Role')
			->display_as('birthdate', 'Birthdate')
			->display_as('email', 'E-mail Address')
			->display_as('gender', 'Gender')
			->display_as('civil_status', 'Civil Status')
			->display_as('father_name', 'Father')
			->display_as('mother_name', 'Mother')
			->display_as('spouse_name', 'Spouse')
			->display_as('children_num', 'No. of children')
			->display_as('employment_status', 'Employment')
			->display_as('hire_date', 'Hire Date')
			->display_as('termination_date', 'Termination Date')
			->display_as('notes', 'Notes/Others')
			->display_as('userStatus', 'PERSONAL INFORMATION')
			->display_as('familybackground', 'FAMILY BACKGROUND')
			->display_as('spouse_child1', 'Name Of Child(fullname)')
			->display_as('spouse_child2', 'Name Of Child(fullname)')
			->display_as('spouse_child3', 'Name Of Child(fullname)')
			->display_as('spouse_child4', 'Name Of Child(fullname)')
			->display_as('spouse_child5', 'Name Of Child(fullname)')
			->display_as('spouse_child_bday1', 'Birth Date')
			->display_as('spouse_child_bday2', 'Birth Date')
			->display_as('spouse_child_bday3', 'Birth Date')
			->display_as('spouse_child_bday4', 'Birth Date')
			->display_as('spouse_child_bday5', 'Birth Date')
			->display_as('educationalbackground', 'EDUCATIONAL BACKGROUND')
			->display_as('name_ext', 'Name Ext (e.g jr,sr)')
			
			->display_as('elem_name', 'Elementary Name Of School')
			->display_as('voc_name', 'Vocational Name Of School')
			->display_as('secondary_name', 'Secondary Name Of School')
			->display_as('college_name', 'College Name Of School')
			->display_as('grad_name', 'Masteral Name Of School')
			
			->display_as('elem_course', 'Elementary Degree Course')
			->display_as('voc_course', 'Vocational Degree Course')
			->display_as('secondary_course', 'Secondary Degree Course')
			->display_as('college_course', 'College Degree Course')
			->display_as('grad_course', 'Masteral Degree Course')
			
			->display_as('elem_year', 'Elementary Year Graduated (if graduated)')
			->display_as('voc_year', 'Vocational Year Graduated (if graduated)')
			->display_as('secondary_year', 'Secondary Year Graduated (if graduated)')
			->display_as('college_year', 'College Year Graduated (if graduated)')
			->display_as('grad_year', 'Masteral Year Graduated (if graduated)')
			
			->display_as('elem_units', 'Elementary Highest Grade/Level units earned (if not graduate)')
			->display_as('voc_units', 'Vocational Highest Grade/Level units earned (if not graduate)')
			->display_as('secondary_units', 'Secondary Highest Grade/Level units earned (if not graduate)')
			->display_as('college_units', 'College Highest Grade/Level units earned (if not graduate)')
			->display_as('grad_units', 'Masteral Highest Grade/Level units earned (if not graduate)')
			
			->display_as('elem_attendance_from', 'Elementary Inclusive Date of Attendance From')
			->display_as('voc_attendance_from', 'Vocational Inclusive Date of Attendance From')
			->display_as('secondary_attendance_from', 'Secondary Inclusive Date of Attendance From')
			->display_as('college_attendance_from', 'College Inclusive Date of Attendance From')
			->display_as('grad_attendance_from', 'Masteral Inclusive Date of Attendance From')
			
			->display_as('elem_attendance_to', 'Elementary Inclusive Date of Attendance To')
			->display_as('voc_attendance_to', 'Vocational Inclusive Date of Attendance To')
			->display_as('secondary_attendance_to', 'Secondary Inclusive Date of Attendance To')
			->display_as('college_attendance_to', 'College Inclusive Date of Attendance To')
			->display_as('grad_attendance_to', 'Masteral Inclusive Date of Attendance To')
			
			->display_as('elem_honors_recieved', 'Elementary Scholarship/Academic Honors Recieved')
			->display_as('voc_honors_recieved', 'Vocational Scholarship/Academic Honors Recieved')
			->display_as('secondary_honors_recieved', 'Secondary Scholarship/Academic Honors Recieved')
			->display_as('college_honors_recieved', 'College Scholarship/Academic Honors Recieved')
			->display_as('grad_honors_recieved', 'Masteral Scholarship/Academic Honors Recieved')
			->display_as('educationalbackground', 'EDUCATIONAL BACKGROUND');
		
		// Settings for edit and add
		$c->fields('given_id',
				   'userStatus',
				   'last_name',
				   'first_name',
				   'middle_name',
				   'name_ext',
				   'role',
				   'birthdate',
				   'birthplace',
					'email',
					'gender',
					'civil_status',
					'citizenship',
					'height',
					'weight',
					'blood_type',
					'religion',
					'sss_id_no',
					'pagibig_no',
					'philhealth_no',
					'residential_address',
					'residential_zip',
					'residential_telno',
					'permanent_address',
					'permanent_zip',
					'permanent_telno',
					'familybackground',
					'father_firstname', 
					'father_surname', 
					'father_middlename', 
					'mother_firstname',
					'mother_surname',
					'mother_middlename',
					'spouse_firstname',
					'spouse_surname',
					'spouse_middlename',
					'spouse_child1',
					'spouse_child_bday1',
					'spouse_child2',
					'spouse_child_bday2',
					'spouse_child3',
					'spouse_child_bday3',
					'spouse_child4',
					'spouse_child_bday4',
					'spouse_child5',
					'spouse_child_bday5',
					'educationalbackground',
					'ELEMENTARY',
					'elem_name',
					'elem_course',
					'elem_year',
					'elem_units',
					'elem_attendance_from',
					'elem_attendance_to',
					'elem_honors_recieved',
					'SECONDARY',
					'secondary_name',
					'secondary_course',
					'secondary_year',
					'secondary_units',
					'secondary_attendance_from',
					'secondary_attendance_to',
					'secondary_honors_recieved',
					'VOCATIONAL',
					'voc_name',
					'voc_course',
					'voc_year',
					'voc_units',
					'voc_attendance_from',
					'voc_attendance_to',
					'voc_honors_recieved',
					'COLLEGE',
					'college_name',
					'college_course',
					'college_year',
					'college_units',
					'college_attendance_from',
					'college_attendance_to',
					'college_honors_recieved',
					'GRADUATE/MASTERAL',
					'grad_name',
					'grad_course',
					'grad_year',
					'grad_units',
					'grad_attendance_from',
					'grad_attendance_to',
					'grad_honors_recieved',
					'employment_status',
					'hire_date',
					'termination_date',  
					'notes',
					'id',
					'emp_id');

		$c->required_fields('given_id','last_name', 'first_name', 'middle_name','role');

/*		$c->field_type('role', 'dropdown',
							array('president' => 'President',
							'admin' => 'Administrator',
							'vice-principal' => 'Vice Principal',
							'teacher' => 'Teacher',
							'hrd' => 'Human Resource',
							'finance' => 'Finance',
							'evaluation' => 'Evaluation',
							'registrar' => 'Registrar',
							'guidance' => 'Guidance Counsellor',
							'librarian' => 'Librarian',
							'custodian' => 'Custodian',
							'cashier' => 'Cashier',
							'encoder' => 'Encoder'));*/
		$c->field_type('role', 'dropdown',$this->M_departments->get_dropdown());
		$c->field_type('civil_status', 'dropdown',
							array('single' => 'Single',
							'married' => 'Married',
							'widowed' => 'Widowed',
							'widower' => 'Widower'));
		$c->field_type('employment_status', 'dropdown',
							array('permanent' => 'Permanent',
							'contractual' => 'Contractual',
							'part-time' => 'Part-time'));
		$c->field_type('gender', 'dropdown',
							array('M' => 'Male',
							'F' => 'Female'));
		$c->field_type('userStatus', 'readonly');
		$c->field_type('familybackground', 'readonly');
		$c->field_type('educationalbackground', 'readonly');
		$c->field_type('SECONDARY', 'readonly');
		$c->field_type('ELEMENTARY', 'readonly');
		$c->field_type('VOCATIONAL', 'readonly');
		$c->field_type('COLLEGE', 'readonly');
		$c->field_type('GRADUATE/MASTERAL', 'readonly');
		$c->field_type('id', 'hidden');
		$c->field_type('emp_id', 'hidden');
		$c->callback_edit_field('given_id',array($this,'given_name_callback'));

		// Set settings for upload
		$c->set_field_upload('contract_filepath', 'repository/contracts');

		//set rules
		$c->set_rules('last_name', 'last name', 'alpha_space_added');
		$c->set_rules('first_name', 'first name', 'alpha_space_added');
		$c->set_rules('middle_name', 'middle name', 'alpha_space_added');

		//Remove some items not needed
		$c->unset_export()
		->unset_print()
		->unset_jquery()
		->unset_jquery_ui()
		->unset_read()
		->unset_delete();
		
		// Callbacks
		$c->callback_insert(array($this, 'insert_employee'));
		$c->callback_update(array($this, 'update_employee'));
		$c->callback_before_upload(array($this, 'check_url'));
		$c->callback_after_upload(array($this, 'save_url'));

		// Add recycle functions
		$c->add_action('Move to Bin', '', 'employee_settings/recycle_employee', 'ui-icon-trash');
		$output = $c->render();
		$this->view_data['output'] = $output;
	}
	
	function profilePicture(){
		$this->load->helper('student_photo');
		$profile = func_get_args();
		return '<img src="'.employee_thumbs(__link(intval($profile[1]->emp_id)),$profile[1]->gender).'" width="80" height="80">';		
	}

	/* Callbacks for manage_employees() */
	function insert_employee($data) // $data is an array
	{
		return $this->M_employees->insert_employee($data);
	}
	
	function update_employee($data)
	{
		return $this->M_employees->update_employee($data);
	}
	
	function check_url($files_to_upload, $field_info)
	{
		return $this->M_employees->check_url($files_to_upload, $field_info);
	}
	
	function given_name_callback($value, $p_key, $user_type)
	{
		return $this->M_employees->given_name_callback($value, $p_key, $user_type);
	}
			
	/* End of callbacks for get_all_employees() */
	/*=== End of get_all_employees() ===*/
	
	function employee_bin()
	{
		if($this->session->userdata('userType') !== 'hrd' AND $this->session->userdata('userType') !== 'admin' AND $this->session->userdata('userType') !== 'president')
		{
			show_error('Illegal user type.', 403);
		}
		
		$c = new grocery_CRUD();
		$c->set_theme('datatables'); // theme datatables or flexigrid
		$c->where('userStatus', 'inactive');
		$c->set_table('employees'); // set table
		$c->set_subject('Employees');
		$c->order_by('last_name', 'asc');
		$c->display_as('last_name','Last Name')
			 ->display_as('first_name','First Name')
			 ->display_as('middle_name','Middle Name')
			 ->display_as('role','Role')
			 ->display_as('given_id','Given ID');
			 
		$c->columns('given_id','last_name','first_name','middle_name', 'role');
		$this->load->model('M_departments');
		$c->field_type('role', 'dropdown',$this->M_departments->get_dropdown());
		
		//$c->field_type('role', 'dropdown',
		//					array('president' => 'President',
		//					'admin' => 'Administrator',
		//					'teacher' => 'Teacher',
		//					'hrd' => 'Human Resource',
		//					'finance' => 'Finance',
		//					'evaluation' => 'Evaluation',
		//					'registrar' => 'Registrar',
		//					'cashier' => 'Cashier',
		//					'encoder' => 'Encoder'));
		
		$c->add_action('Restore', '', 'employee_settings/restore_employee','ui-icon-arrowreturn-1-w');
		
		$c->unset_add()
			->unset_edit()
			->unset_export()
			->unset_print()
			->unset_texteditor();
			
		$c->callback_delete(array($this, 'destroy_employee'));
		
		
		$output = $c->render(); // render
		$this->view_data['output'] = $output;
	}
	
	private function __change_username($uname, $user_id)
	{
		$flag = '';
		if($this->M_users->check_duplicates($uname, $user_id)) // TRUE if no duplicate, FALSE otherwise
		{
			$data = array(
					'username'=>$uname,
					'updated_at'=>NOW);
			if($this->M_users->update_user($user_id, $data))
			{
				$flag = $this->M_employees->update_given_id($uname, $user_id);
			}else
			{
				$flag = FALSE;
			}
		}else
		{
			$flag = 'duplicate';
		}
		return $flag;
	}
	
	private function __change_password($pword, $user_id)
	{
		return $this->M_users->change_pass($pword, $user_id);
	}
	
	private function __prepare_display($field_obj)
	{
		$needle = array('set(', ')');
		foreach($field_obj AS $field)
		{
			if(strpos($field->Type, "set(") !== FALSE)
			{
				$temp = str_replace($needle, "", $field->Type);
				$set = str_getcsv($temp);
				$display_arr[$field->Field] = array('type'=>'set',
													'set'=>$this->__prepare_options($set),
													'display'=>$this->__display_name($field->Field));
			}else
			{
				$display_arr[$field->Field] = array(
										'type'=>$field->Type,
										'display'=>$this->__display_name($field->Field));
			}
		}
		return $display_arr;
	}
	
	private function __display_name($field_name)
	{
		switch($field_name)
		{
			case 'children_num':
				$new = 'No. of Children';
				break;
			default:
				$new = ucwords(str_replace("_", " ", $field_name));
				break;
		}
		return $new;
	}
	
	private function __prepare_options($options)
	{
		$new_opt = "";
		for($i = 0; $i < count($options); $i++)
		{
			$temp = str_replace("'","",$options[$i]);
			switch($temp)
			{
				case 'M':
					$new_opt[$options[$i]] = 'Male';
					break;
				case 'F':
					$new_opt[$options[$i]] = 'Female';
					break;
				case 'single':
					$new_opt[$options[$i]] = 'Single';
					break;
				case 'married':
					$new_opt[$options[$i]] = 'Married';
					break;
				case 'widowed':
					$new_opt[$options[$i]] = 'Widowed';
					break;
				case 'widower':
					$new_opt[$options[$i]] = 'Widower';
					break;
				case 'permanent':
					$new_opt[$options[$i]] = 'Permanent';
					break;
				case 'part-time':
					$new_opt[$options[$i]] = 'Part-time';
					break;
				case 'contractual':
					$new_opt[$options[$i]] = 'Contractual';
					break;
				case 'active':
					$new_opt[$options[$i]] = 'Active';
					break;
				case 'inactive':
					$new_opt[$options[$i]] = 'Inactive';
					break;
				case 'deleted':
					$new_opt[$options[$i]] = 'Deleted';
					break;
				default:
					$new_opt[$options[$i]] = $options[$i];
					break;
			}
		}
		return $new_opt;
	}
	
	private function __prepare_form_validation($elements)
	{
		$form_config = array();
		foreach($elements AS $e => $val)
		{
			switch($e)
			{
				case 'email':
					$config = array(
						'field'=>'profile[' . $e . ']',
						'label'=>$this->__display_name($e),
						'rules'=>'valid_email');
					break;
				case 'children_num':
					$config = array(
						'field'=>'profile[' . $e . ']',
						'label'=>'No. of Children',
						'rules'=>'');
					break;
				case 'termination_date':
					$config = array(
						'field'=>'profile[' . $e . ']',
						'label'=>$this->__display_name($e),
						'rules'=>'');
					break;
				case 'spouse_name':
					$config = array(
						'field'=>'profile[' . $e . ']',
						'label'=>$this->__display_name($e),
						'rules'=>'');
					break;
				case 'notes':
					$config = array(
						'field'=>'profile[' . $e . ']',
						'label'=>$this->__display_name($e),
						'rules'=>'');
					break;
				default:
					$config = array(
						'field'=>'profile[' . $e . ']',
						'label'=>$this->__display_name($e),
						'rules'=>'required');
					break;
			}
			array_push($form_config, $config);
		}
		return $form_config;
	}
	private function _format_date_display($date)
	{
		if($date === '0000-00-00')
		{
			$date = "";
		}else
		{
			$date = date("d/m/Y", strtotime($date));
		}
		return $date;
	}
	
	function recycle_employee($id = '')
	{
		$message = '';
		$user_type = $this->session->userdata('userType');
		if($id > 0)
		{
			if($this->M_employees->recycle_employee($id) == FALSE)
			{
				redirect('employee_settings/manage_employees','location');
			}else
			{
				redirect('employee_settings/manage_employees','location');
			}
		}else
		{
			redirect('employee_settings/manage_employees','location');
		}
	}
	
	function restore_employee($id = '')
	{
		$message = '';
		if($id > 0)
		{
			if($this->M_employees->restore_employee($id) == FALSE)
			{
				redirect('employee_settings/employee_bin','location');
			}else
			{
				redirect('employee_settings/employee_bin','location');
			}
		}else
		{
			redirect('employee_settings/employee_bin','location');
		}
		
	}

	function change_emp_password($hash = '')
	{
		$x = $this->hs->decrypt($hash);
		if(IS_AJAX && $x)
		{	
			$post = $this->input->post();

			$this->load->model('M_users');
			$result = $this->M_users->change_employee_user_password_by_emp_id($post,$x[0]);
			header('Content-Type: application/json');
			echo json_encode($result);
			exit();
		}
	}
	
	public function manage_employees_access()
	{
		$this->load->model(array('M_employee_access_grade_levels'));
		
		$this->view_data['emp_user_data'] = $this->M_employee_access_grade_levels->get_employees();
		$this->view_data['access_levels'] = $this->M_employee_access_grade_levels->get_access_level();
	}
	
	public function edit_manage_employees_access($id)
	{
		$this->load->model(array('M_employee_access_grade_levels'));
		
		if($this->input->post('Update'))
		{
			$grade_levels = $this->input->post('grade_level');
			$emp_id = $this->input->post('emp_id');
			$result_del = $this->M_employee_access_grade_levels->delete_access_level($emp_id);
			$insert_values = array();
			if($result_del){
				if($grade_levels){
					foreach($grade_levels as $k => $v)
					{
						$data['emp_id'] = $emp_id;
						$data['level_id'] = $v;
						array_push($insert_values, $data);
					}
				}
			}
			
			if($insert_values)
			{
				$this->db->insert_batch('employee_access_grade_levels', $insert_values); 
				if($this->db->affected_rows()){
					$this->view_data['system_message'] = $this->notifier->build_system_message('success', 'Success.');
				}else{
					$this->view_data['system_message'] = $this->notifier->build_system_message('error', 'Unable to update grade level access. Try again.');
				}
			}
		}
		
		$this->view_data['emp_user_data'] = $this->M_employee_access_grade_levels->get_employees($id);
		$this->view_data['access_levels'] = $this->M_employee_access_grade_levels->get_access_level($id);
		$this->view_data['levels'] = $this->M_employee_access_grade_levels->get_level_grades();
	}
}
?>